package com.huidz.calendar.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.transition.Slide;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.google.android.material.tabs.TabLayout;
import com.huidz.calendar.R;
import com.huidz.calendar.ViewPagerAdapter;
import com.huidz.calendar.daysfragment.JinianriFragment;
import com.huidz.calendar.daysfragment.LowdayFragment;
import com.huidz.calendar.daysfragment.NiecdayFragment;
import com.huidz.calendar.mainfragment.RemindFragment;
import com.huidz.calendar.util.Apiutils;
import com.huidz.calendar.util.Url;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

public class AddActivity extends AppCompatActivity implements View.OnClickListener {

    private ViewPager home_pager;
    private List<Fragment> fraglist;
    //
//    //ViewPager适配器
    private ViewPagerAdapter pagerAdapter;
    //底部导航栏的四个rela
    /*****************************/
    private TabLayout mytab;
    private TextView comeback, return_rela_text;
    //共享给自己的fragment的数据
    private int index = 0;

    public static int indexs = 0;//用于获取当前的下标，判断完成的是那个页面的值

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Slide slide = new Slide(Gravity.BOTTOM);
        slide.setDuration(200L);//间歇时间
        getWindow().setEnterTransition(slide);
        setContentView(R.layout.activity_add);
        inti();
    }

    /**
     * 初始化加载调用方法
     */
    public void inti() {
        Intent getindex = getIntent();
        index = Integer.parseInt(getindex.getStringExtra("index"));
        home_pager = findViewById(R.id.home_pager);
        comeback = findViewById(R.id.title_comeback);
        return_rela_text = findViewById(R.id.title_return);
        return_rela_text.setOnClickListener(this);
        comeback.setOnClickListener(this);
        mytab = findViewById(R.id.mytab);
        mytab.addTab(mytab.newTab().setText("备忘录"));
        mytab.addTab(mytab.newTab().setText("生日"));
        mytab.addTab(mytab.newTab().setText("纪念日"));
        mytab.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                // 开启Fragment事务
                if (tab.getText().equals("备忘录")) {
                    home_pager.setCurrentItem(0);
                }
                if (tab.getText().equals("生日")) {
                    home_pager.setCurrentItem(1);
                }
                if (tab.getText().equals("纪念日")) {
                    home_pager.setCurrentItem(2);
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        AddFragment();
    }

    public class MyPagerChangeListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            mytab.getTabAt(position).select();
            indexs = position;
//            Seleced(position);
        }

        @Override
        public void onPageScrollStateChanged(int state) {
        }
    }


    /**
     * 用于绑定fragment
     */
    public void AddFragment() {
        //添加frag到集合中
        fraglist = new ArrayList<>();
        fraglist.add(new NiecdayFragment());
        fraglist.add(new LowdayFragment());
        fraglist.add(new JinianriFragment());
        home_pager.setOnPageChangeListener(new MyPagerChangeListener());
        //绑定适配器
        pagerAdapter = new ViewPagerAdapter(getSupportFragmentManager(), fraglist);
        home_pager.setAdapter(pagerAdapter);
        home_pager.setCurrentItem(index);
        home_pager.setOffscreenPageLimit(3);
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_comeback:
                onBackPressed();
                break;
            case R.id.title_return:
                switch (indexs) {
                    case 0:
                        if (NiecdayFragment.edit.getText().toString().equals("")) {
                            Apiutils.SetToast(AddActivity.this, "请填写提醒内容");
                        } else
                            okHttp_postFromParameters(1 + "", NiecdayFragment.chongfuid + "", NiecdayFragment.datetime_s, "", NiecdayFragment.edit.getText().toString(), "", NiecdayFragment.mrak.getText().toString(), NiecdayFragment.address.getText().toString());
                        break;
                    case 1:
                        if (LowdayFragment.edit.getText().toString().equals("")) {
                            Apiutils.SetToast(AddActivity.this, "请填写寿星名字");
                        } else
                            okHttp_postFromParameters(2 + "", 0 + "", LowdayFragment.datetime_s, LowdayFragment.edit.getText().toString(),"", "", LowdayFragment.beizhu.getText().toString(),"");
                        break;

                    case 2:
                        if (JinianriFragment.edit.getText().toString().equals("")) {
                            Apiutils.SetToast(AddActivity.this, "请填写纪念日内容");
                        } else
                            okHttp_postFromParameters(3 + "", 0 + "", JinianriFragment.datetime_s, "","", JinianriFragment.edit.getText().toString(), JinianriFragment.beizhu.getText().toString(),"");
                        break;
                }
//                this.finish();
                break;
//            case R.id.title_ji_rela:
//                home_pager.setCurrentItem(0);
//                Seleced(1);
//
//                break;
//            case R.id.title_yi_rela:
//                home_pager.setCurrentItem(1);
//                Seleced(0);
//                break;
        }
    }
//    public void Seleced(int i){
//        if(i==0){
//            title_yi_h.setVisibility(View.INVISIBLE);
//            title_ji_h.setVisibility(View.GONE);
//        }else{
//            title_yi_h.setVisibility(View.GONE);
//            title_ji_h.setVisibility(View.INVISIBLE);
//        }
//    }

    public static long firstTime = 0;

    public void okHttp_postFromParameters(String type, String repeatetype, String remindtime, String birthdayperson, String memcontent, String commem, String mark, String address) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient okHttpClient = new OkHttpClient();
                    RequestBody formBody = new FormBody.Builder().add("logintoken", Url.USER_TOKEN).add("type", type).add("repeatetype", repeatetype).add("remindtime", remindtime).add("birthdayperson", birthdayperson).add("memcontent", memcontent).add("commem", commem).add("mark", mark).add("address", address)
                            .build();
                    Request request = new Request.Builder().url(Url.ADDTIXING).post(formBody).build();
                    okhttp3.Response response = okHttpClient.newCall(request).execute();
                    String msg = response.body().string();
                    Message message = new Message();
                    message.obj = msg;
                    gethot.sendMessage(message);
                } catch (
                        Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public Handler gethot = new Handler() {
        public void handleMessage(Message msg) {
            String msgs = null;
            try {
                Apiutils.setlog("msg:"+msg.obj.toString());
                JSONObject success_Object = null;
                if (msg.obj != null) {
                    success_Object = new JSONObject(msg.obj.toString());
                    String code = success_Object.getString("code");
                    msgs = success_Object.getString("msg");
                    if (code.equals("1")) {
                        onBackPressed();
                        RemindFragment.shuaxing=true;
                        Apiutils.SetToast(AddActivity.this, msgs + "");
                    } else
                        Apiutils.SetToast(AddActivity.this, msgs + "");
                }

            } catch (
                    Exception e) {
                e.printStackTrace();
            }
        }
    };

}
